package com.example.week10_advanceui2;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.EditText;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TextBookActivity extends AppCompatActivity {

    final String FILE_NAME="memo.txt";

    boolean ischanged=false;

    EditText editFileEdt,fielPathEdt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_book);

        editFileEdt=(EditText) findViewById(R.id.editFileEdt);
        fielPathEdt=(EditText) findViewById(R.id.fielPathEdt);

        editFileEdt.addTextChangedListener(textChangedListener);
    }

    //5.2.1
       /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
         super.onCreateOptionsMenu(menu);
        //分两组

        int group1=1;
        int group2=2;

        menu.add(group1,201,1,"打开文件");
        menu.add(group1,202,2,"保存文件");
        menu.add(group2,203,3,"退出应用");
        menu.add(group2,204,4,"关于我们");
        return true;
    }*/

    //5.2.2选项菜单
     @Override
     public boolean onCreateOptionsMenu(Menu menu)
     {
         //一个menu有多个子菜单
         SubMenu subMenu=menu.addSubMenu(0,Menu.NONE,Menu.NONE,"文件操作");
         //子菜单有多个菜单项
         MenuItem openItem=subMenu.add(2,201,1,"打开文件");

         openItem.setIcon(R.drawable.open);

         MenuItem saveItem=subMenu.add(2,202,2,"保存文件");
         saveItem.setIcon(R.drawable.save);

         menu.add(2,203,3,"退出应用");
         menu.add(2,204,4,"关于");
         //显示菜单请返回true
         return true;
     }

    //定义事件监听器,处理各菜单项（子菜单项）被选中时的业务
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case 201://读文件
                readFile();
                break;
            case 202: //保存文件后，重置文件内容被修改标志writeFile
                writeFile();
                ischanged=false;
                break;
            case 203: //退出处理：若有改动需确认是否保存
                if(ischanged)
                {
                    //如果有改动
                    AlertDialog.Builder alterDialog=new AlertDialog.Builder(TextBookActivity.this);
  alterDialog.setTitle("提示").setMessage("文件有改动，是否保存?").setPositiveButton("保存", new DialogInterface.OnClickListener()
  {
      @Override
      public void onClick(DialogInterface dialog, int which)
      {
          writeFile();
          finish();
      }
  }).setNegativeButton("不保存", new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
          //直接退出
          finish();
      }
  }).create().show();

                }
                break;

            case 204:
                AlertDialog.Builder alterDialog= new AlertDialog.Builder(TextBookActivity.this);
                alterDialog.setTitle("提示").setMessage("通过这个Demo，学会各种菜单。").setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create().show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }



    //写入文件
    public void writeFile()
    {
        //取得文件内容
        String str=editFileEdt.getText().toString();

        try {
            FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);

            //定义输出流对象并打开文件夹
            fos.write(str.getBytes());
            //关闭文件
            fos.close();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读文件内容
    private void readFile() {

    try
    {
        FileInputStream fis=openFileInput(FILE_NAME);

        byte[] buff = new byte[1024];
        //已读入字节数
        int hasRead = 0;
        //定义并初始字符串构造器对象
        StringBuilder sb = new StringBuilder();
        //循环将文件内容读入缓冲区并合并到字符串构造器
        while ((hasRead = fis.read(buff)) > 0) {
            sb.append(new String(buff,0,hasRead));
        }
        fis.close();
        //更新组件内容
        editFileEdt.setText(sb);
        //更新文件路径信息
        fielPathEdt.setText(getFilesDir().toString());

    }catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }catch (IOException e){
        e.printStackTrace();
    }
 }
  private TextWatcher textChangedListener=new TextWatcher()
  {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {

      }
      //当文本改变后，将已修改标记改为true
      @Override
      public void afterTextChanged(Editable s) {
              ischanged=true;
      }
  };
}
